<?php
/**
 * Example 1
 * 
 * Downloading thumbnail pictures of cats from the flickr.com
 * (10 search result pages) and saving them in the 'cats' directory.
 * 
 * In this example:
 * - Attaching requests to the HttpClient object
 * - Using RequestCompleted event callback function
 * - Setting output file pathes
 */


use Curly\Request;
use Curly\HttpClient;

require "../lib/Loader.php";

// Create images directory
if( !is_dir( "./cats" ) )
{
    mkdir( "./cats" );
}

// Start timer
$start = microtime( true );

// Create a HttpClient adapter object
$client = HttpClient::create();

// Create and attach a Request object for each search result page 
for( $page = 1; $page <= 10; $page++ )
{
    $request = new Request( "http://www.flickr.com/search/?q=cat&page={$page}" );
    $request->requestCompletedEvent()->attachFunc( function( $sender ) use( $page ) {
        // Find thumbnail pictures
        preg_match_all( "~<img src=\"(?<imgUrl>http://farm([0-9]+).static.flickr.com/([^/]+)/([^/\"]+))\"~", $sender->getResponse()->getContent(), $images, PREG_SET_ORDER );
        
        echo "There are " . count( $images ) . " pictures on page {$page}<br>";
        
        foreach( $images as $image )
        {
            // Create an unique output file path
            $i = 0;
            do 
            {
                $imgFilePath = "./cats/{$image[2]}_{$image[3]}_{$i}_{$image[4]}";
                $i++;
            }
            while( file_exists( $imgFilePath ) );
            
            // Create and attach a Request object for each picture
            $imgRequest = new Request( $image["imgUrl"] );
            $imgRequest->setOutputFilePath( $imgFilePath );

            $sender->getClient()->attach( $imgRequest );
        }
    } );
    
    $client->attach( $request );
}

// Run client
$client->execute();

// Stop timer and show time
$end = microtime( true );
echo "<br>Total execution time: " . round( $end - $start, 3 ) . " s";